package com.suray.attendance.contacts.service.impl;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiAttendanceGetcolumnvalRequest;
import com.dingtalk.api.response.OapiAttendanceGetcolumnvalResponse;
import com.suray.attendance.common.utils.LoggerUtil;
import com.suray.attendance.contacts.service.AttendanceService;
import com.suray.attendance.model.bean.AttendanceDataInfo;
import com.suray.attendance.model.enums.dingding.DingColumnEnum;
import com.taobao.api.ApiException;
import com.taobao.api.internal.util.StringUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Description:
 * Author: linyu
 * Date: 2023/11/21
 */
@Service
public class AttendanceServiceImpl implements AttendanceService {

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * @description: 调用钉钉的考勤打卡接口获取
     * @author: jianglinyu
     * @date: 2023/11/21 11:26
     * @return
     */
    @Override
    public Map<Date, AttendanceDataInfo> getAttendanceListRecordByUserIdFromDingDing(String accessToken, String userId, LocalDateTime checkDateFrom, LocalDateTime checkDateTo) {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/attendance/getcolumnval");
        OapiAttendanceGetcolumnvalRequest req = new OapiAttendanceGetcolumnvalRequest();
        req.setUserid(userId);
        List<Long> columnIdList = new ArrayList<>(2);
        columnIdList.add(DingColumnEnum.工作时长.getColumnId());
        columnIdList.add(DingColumnEnum.考勤结果.getColumnId());
        columnIdList.add(DingColumnEnum.上班1打卡结果.getColumnId());
        columnIdList.add(DingColumnEnum.上班1打卡时间.getColumnId());
        columnIdList.add(DingColumnEnum.下班1打卡结果.getColumnId());
        columnIdList.add(DingColumnEnum.下班1打卡时间.getColumnId());
        columnIdList.add(DingColumnEnum.上班2打卡结果.getColumnId());
        columnIdList.add(DingColumnEnum.上班2打卡时间.getColumnId());
        columnIdList.add(DingColumnEnum.下班2打卡结果.getColumnId());
        columnIdList.add(DingColumnEnum.下班2打卡时间.getColumnId());
        columnIdList.add(DingColumnEnum.上班3打卡结果.getColumnId());
        columnIdList.add(DingColumnEnum.上班3打卡时间.getColumnId());
        columnIdList.add(DingColumnEnum.下班3打卡结果.getColumnId());
        columnIdList.add(DingColumnEnum.下班3打卡时间.getColumnId());

        String columnIdListString = Arrays.toString(columnIdList.toArray()).replace("[", "").replace("]", "");
        req.setColumnIdList(columnIdListString); // 固定
        req.setFromDate(StringUtils.parseDateTime(checkDateFrom.format(formatter)));
        req.setToDate(StringUtils.parseDateTime(checkDateTo.format(formatter)));
        OapiAttendanceGetcolumnvalResponse response = null;
        try {
            response = client.execute(req, accessToken);
            if(response!=null && response.getErrmsg().equals("ok")){
                OapiAttendanceGetcolumnvalResponse.ColumnValListForTopVo result = response.getResult();
                List<OapiAttendanceGetcolumnvalResponse.ColumnValForTopVo> columnVals = result.getColumnVals();
                Map<Date, AttendanceDataInfo> attendanceDataInfoMap = new ConcurrentHashMap<>();
                columnVals.stream().forEach(columnValForTopVo -> {
                    if (DingColumnEnum.工作时长.getColumnId().intValue()== columnValForTopVo.getColumnVo().getId().intValue()) {
                        List<OapiAttendanceGetcolumnvalResponse.ColumnDayAndVal> workDurationResponse = columnValForTopVo.getColumnVals();
                        workDurationResponse.stream().forEach(workDuration -> {
                            Date date = workDuration.getDate();
                            String workTimeString = workDuration.getValue();
                            Double workTime = (Double.valueOf(workTimeString)*60.0);
                            attendanceDataInfoMap.put(date, new AttendanceDataInfo(date, workTime.longValue(), userId));
//                            attendanceDataInfoMap.computeIfAbsent(date, k -> new AttendanceDataInfo(date, workTime.longValue(), userId));
                        });
                    }
                    if (DingColumnEnum.考勤结果.getColumnId().intValue()== columnValForTopVo.getColumnVo().getId().intValue()){
                        List<OapiAttendanceGetcolumnvalResponse.ColumnDayAndVal> attendanceResultResponse = columnValForTopVo.getColumnVals();
                        attendanceResultResponse.stream().forEach(attendanceResult -> {
                            Date date = attendanceResult.getDate();
                            String outcome = attendanceResult.getValue();
                            if (attendanceDataInfoMap.containsKey(date)) {
                                AttendanceDataInfo attendanceDataInfo = attendanceDataInfoMap.get(date);
                                attendanceDataInfo.setOutcome(outcome);
                            }
//                            attendanceDataInfoMap.computeIfPresent(date, (k, v) -> {
//                                v.setOutcome(outcome);
//                                return v;
//                            });
                        });
                    }
                    if (DingColumnEnum.上班1打卡时间.getColumnId().intValue()== columnValForTopVo.getColumnVo().getId().intValue()){
                        List<OapiAttendanceGetcolumnvalResponse.ColumnDayAndVal> startWorkTimeResponse = columnValForTopVo.getColumnVals();
                        startWorkTimeResponse.stream().forEach(attendanceResult -> {
                            Date date = attendanceResult.getDate();
                            String startWorkTime = attendanceResult.getValue();
                            if (attendanceDataInfoMap.containsKey(date)) {
                                AttendanceDataInfo attendanceDataInfo = attendanceDataInfoMap.get(date);
                                attendanceDataInfo.setStartWorkTime(startWorkTime);
                            }
                        });
                    }
                    if (DingColumnEnum.上班1打卡结果.getColumnId().intValue()== columnValForTopVo.getColumnVo().getId().intValue()){
                        List<OapiAttendanceGetcolumnvalResponse.ColumnDayAndVal> startTimeResultResponse = columnValForTopVo.getColumnVals();
                        startTimeResultResponse.stream().forEach(attendanceResult -> {
                            Date date = attendanceResult.getDate();
                            String startTimeResult = attendanceResult.getValue();
                            if (attendanceDataInfoMap.containsKey(date)) {
                                AttendanceDataInfo attendanceDataInfo = attendanceDataInfoMap.get(date);
                                attendanceDataInfo.setStartWorkResult(startTimeResult);
                            }
                        });
                    }
                    if (DingColumnEnum.下班1打卡时间.getColumnId().intValue()== columnValForTopVo.getColumnVo().getId().intValue()){
                        List<OapiAttendanceGetcolumnvalResponse.ColumnDayAndVal> endWorkTimeResponse = columnValForTopVo.getColumnVals();
                        endWorkTimeResponse.stream().forEach(attendanceResult -> {
                            Date date = attendanceResult.getDate();
                            String endWorkTime = attendanceResult.getValue();
                            if (attendanceDataInfoMap.containsKey(date)) {
                                AttendanceDataInfo attendanceDataInfo = attendanceDataInfoMap.get(date);
                                attendanceDataInfo.setEndWorkTime(endWorkTime);
                            }
                        });
                    }
                    if (DingColumnEnum.下班1打卡结果.getColumnId().intValue()== columnValForTopVo.getColumnVo().getId().intValue()){
                        List<OapiAttendanceGetcolumnvalResponse.ColumnDayAndVal> endWorkTimeResultResponse = columnValForTopVo.getColumnVals();
                        endWorkTimeResultResponse.stream().forEach(attendanceResult -> {
                            Date date = attendanceResult.getDate();
                            String endWorkTimeResult = attendanceResult.getValue();
                            if (attendanceDataInfoMap.containsKey(date)) {
                                AttendanceDataInfo attendanceDataInfo = attendanceDataInfoMap.get(date);
                                attendanceDataInfo.setEndWorkResult(endWorkTimeResult);
                            }
                        });
                    }

                });
                return attendanceDataInfoMap;
            }
        } catch (ApiException e) {
            LoggerUtil.error(e.getMessage(),AttendanceServiceImpl.class);
            e.printStackTrace();
        }
        return null;
    }


}
